package com.itheima.web.service.impl.ums;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.ums.UmsMenuDto;
import com.itheima.result.PageResult;
import com.itheima.result.ResultData;
import com.itheima.service.ums.UmsMenuService;
import com.itheima.vo.ums.UmsMenu;
import com.itheima.web.mapper.ums.UmsMenuMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements UmsMenuService {
    @Autowired
    public UmsMenuMapper umsMenuMapper;

    @Override
    public ResultData listParentId(Integer parentId, Integer pageNum, Integer pageSize) {
        Page<UmsMenu> infoPage=new Page<>(pageNum,pageSize);
        //条件构造器
        LambdaQueryWrapper<UmsMenu> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsMenu::getParentId,parentId);
        this.page(infoPage,lqw);
        return ResultData.ok("操作成功", PageResult.init(infoPage.getCurrent(),pageNum.longValue(),pageSize.longValue(),infoPage.getRecords()));
    }

    @Override
    public ResultData treeList() {
        LambdaQueryWrapper<UmsMenu> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsMenu::getParentId,0);
        List<UmsMenu> list = this.list(lqw);
        List<UmsMenuDto> data = recursion(list);
        return ResultData.ok("操作成功",data);
    }

    @Override
    public void insert(UmsMenu umsMenu) {
        this.save(umsMenu);
    }

    @Override
    public void updateHidden(Integer id, Integer hidden) {
        UmsMenu menu = this.getById(id);
        menu.setHidden(hidden);
        this.updateById(menu);
    }

    private List<UmsMenuDto> recursion(List<UmsMenu> list){
        List<UmsMenuDto> data=null;
        if (list.size()==0||list==null){
            return data;
        }else {
             data = list.stream().map((item) -> {
                UmsMenuDto umsMenuDto = new UmsMenuDto();
                BeanUtils.copyProperties(item, umsMenuDto);
                List<UmsMenu> menuList = this.list(new LambdaQueryWrapper<UmsMenu>().eq(UmsMenu::getParentId, item.getId()));
                recursion(menuList);
                umsMenuDto.setChildren(menuList);
                return umsMenuDto;
            }).collect(Collectors.toList());
        }
        return data;
    }


}
